<?php

namespace App\Http\Controllers;

use SimpleSoftwareIO\QrCode\Facades\QrCode;
use Illuminate\Http\Request;
use App\Models\Licence;
use App\Models\User;
use App\Models\MealShop;
use App\Models\MealCardOrder;
use App\Models\MealUserCard;
use App\Models\MealOrder;
use App\Models\UserFeedback;
use App\Models\JoinInfo;
use App\Models\Share;
use App\Services\OSS;
use DB;

class UserAdminController extends Controller
{
    public $auth = '';

    public function __construct()
    {
        $this->auth = ['0'=>'未认证','1'=>'认证用户','2'=>'饭店商户','3'=>'手机商户'];
    }

    //用户列表
    public function userAll(Request $request) 
    {
        $user = new User;
        $users = $user->getUsers($request,[['reliability','>','-1']]);
         $card = new MealCardOrder;
    	return view('user.userall',['users'=>$users,'auth_de'=>$this->auth,'card'=>$card,'request'=>$request]);
    }

    //餐饮商家用户列表
    public function userShopList(Request $request) 
    {
        $user = new User;
        $users = $user->getUsers($request,[['reliability','=','2']]);
        $card = new MealCardOrder;
        return view('user.usershop',['users'=>$users,'auth_de'=>$this->auth,'card'=>$card,'request'=>$request]);
    }

    //普通用户列表
    public function userList(Request $request) 
    {
        $user = new User;
        $users = $user->getUsers($request,[['reliability','<','2']]);
        $card = new MealCardOrder;
        return view('user.userlist',['users'=>$users,'auth_de'=>$this->auth,'card'=>$card,'request'=>$request]);
    }

    //有意购卡普通用户列表
    public function userListBuyCard(Request $request)
    {
        $user = new User;
        // $users = $user->getUsers($request,[['reliability','<','2']]);
        $users = $user
        ->leftJoin('lexiang_card_order','lexiang_card_order.user_id','=','lexiang_user.user_id')
        ->where(function($q)use($request){
            // ['lexiang_user.reliability','<','2'],
            // ['lexiang_card_order.order_status','=',0],
            $q = $q->where('lexiang_user.reliability','<','2');
            $q = $q->whereRaw('lexiang_card_order.order_status=0 and (select count(*) from lexiang_meal_user_card where lexiang_meal_user_card.users_id=lexiang_user.user_id and lexiang_meal_user_card.card_invalid = 1) = 0');
            return $q;

        })
        ->orWhere(function($q)use($request){
            // ['lexiang_user.reliability','<','2'],
            // ['lexiang_card_order.order_status','=',0],
            $q = $q->where('lexiang_user.reliability','<','2');
            $q = $q->whereRaw('lexiang_card_order.order_status=1 and (select count(*) from lexiang_meal_user_card where lexiang_meal_user_card.users_id=lexiang_user.user_id and lexiang_meal_user_card.card_invalid = 1) = 0');
            return $q;
            
        })
        ->groupBy('lexiang_user.user_id')
        ->selectRaw('lexiang_user.*,null as circle_name,null as sucircle_name,null as share_user_name,null as buy_card_yx')
        ->orderBy('lexiang_user.insert_time','desc')
        ->paginate(15);
        $card = new MealCardOrder;
        return view('user.buycardbut',['users'=>$users,'auth_de'=>$this->auth,'card'=>$card,'request'=>$request]);
    }

    //用户详情
    public function userDetails(Request $request)
    {
        $userid = $request->input('userid',false);
        if(!$userid){
            abort(404,'找不到您想查看的用户信息');
        }
        $user = User::find($userid);
        if(!$user){
            abort(404,'找不到您想查看的用户信息');
        }
        $orders = MealOrder::userList($userid);
        $cards = MealUserCard::userList($userid);
        $picpath = OSS::getPublicObjectURL(config('aliyun.BucketName'),'PictureOfHead');
        $order_status_de = ['-2'=>'已取消','-1'=>'加价未支付','1'=>'已取餐','0'=>'未取餐','2'=>'已超时','3'=>'已取消'];
        $ViewData = ['user'=>$user,'picpath'=>$picpath,'orders'=>$orders,'cards'=>$cards,'order_status'=>$order_status_de];
        $shop = MealShop::where('users_id',$userid)->select('shop_id','shop_name','insert_time')->first();
        if($shop){
            $ViewData['shop'] = $shop;
        }
        return view('user.userdetails',$ViewData);
    }

    /**
     * 退订饭卡
     */
    // public function 


    /**
     * 身份证认证
     */
    public function userIdentification($userid)
    {
        $path = OSS::getPublicObjectURL(config('aliyun.BucketName'),'IdentifyImgs');

        $licen = Licence::where('users_id',$userid)->select('identity_imgs','identity_confirm','licence_id','users_id')->first();

    	return view('user.identification',['licen'=>$licen,'path'=>$path]);
    }

    /**
     * 营业执照认证
     */
    public function userBusinessaction($userid)
    {
        $path = OSS::getPublicObjectURL(config('aliyun.BucketName'),'BusinessImgs');

        $licen = Licence::where('users_id',$userid)->select('business_img','business_confirm','licence_id','users_id')->first();

        return view('user.businesscation',['licen'=>$licen,'path'=>$path]);
    }

    /**
     * 食品安全认证
     */
    public function userFoodpermitaction($userid)
    {
        $path = OSS::getPublicObjectURL(config('aliyun.BucketName'),'FoodpermitImgs');

        $licen = Licence::where('users_id',$userid)->select('foodpermit_img','foodpermit_confirm','licence_id','users_id')->first();

        return view('user.foodpermitcation',['licen'=>$licen,'path'=>$path]);
    }

    /**
     * 认证列表
     */
    public function userIdentifiList(Request $request) 
    {
        $licens = Licence::leftJoin('lexiang_user','lexiang_user.user_id','=','lexiang_licence.users_id')
        ->orWhere('lexiang_licence.identity_confirm',0)
        ->orWhere('lexiang_licence.business_confirm',0)
        ->orWhere('lexiang_licence.foodpermit_confirm',0)
        ->select('lexiang_licence.*','lexiang_user.nicename','lexiang_user.tel')
        ->get();
        return view('user.identifylist',['licens'=>$licens]);
    }

    /**
     * 身份证认证操作
     */
    public function identificationCertificate(Request $request)
    {
        $post = $request->only(['userid','licenceid','status']);
        $status = $post['status'];
        $status_de = ['TG'=>1,'BH'=>2,'JJ'=>3];
        $status_ok = [1,2,3];
        if(!in_array($status_de[$status],$status_ok)){
            return response()->json(['success'=>false,'code'=>'2','message'=>'没有此状态']);
        }
        $licen = Licence::find($post['licenceid']);
        if($licen->identity_confirm!=0){
            return response()->json(['success'=>false,'code'=>'1','message'=>'当前状态无法修改！']);
        }
        $editData = [
            'identity_confirm'=>$status_de[$status]
        ];
        $licence = new Licence();
        $licenresult = $licence->editAction($editData,$post['licenceid']);
        if(!$licenresult){
            return response()->json(['success'=>false,'code'=>'3','message'=>'操作失败，请稍后重试！']);
        }
        $licenData = Licence::find($post['licenceid']);
        if($licenData->identity_confirm==1 && $licenData->business_confirm==1 && $licenData->foodpermit_confirm==1){
            $userresult = (boolean)User::where('user_id',$post['userid'])->update(['reliability'=>2]);
            $mealshop = new MealShop;
            $existsshop = $mealshop->where('users_id',$post['userid'])->exists();
            if(!$existsshop){
                $shopresult = $mealshop->createShop(['shop_tel'=>User::where('user_id',$post['userid'])->value('tel')],$post['userid']);
                $filename = self::createQrcode($shopresult);
                $qrsul = $mealshop->where('shop_id',$shopresult)->update(['shop_qrcode'=>$filename]);
                if($shopresult && $qrsul){
                    return response()->json(['success'=>true,'code'=>0,'message'=>'操作成功']);
                }else{
                    return response()->json(['success'=>false,'code'=>'3','message'=>'操作失败，请稍后重试！']);
                }
            }
            if($userresult){
                return response()->json(['success'=>true,'code'=>0,'message'=>'操作成功']);
            }else{
                return response()->json(['success'=>false,'code'=>'3','message'=>'操作失败，请稍后重试！']);
            }
        }else{
            return response()->json(['success'=>true,'code'=>0,'message'=>'操作成功']);
        }
    }

    /**
     * 营业执照认证操作
     */
    public function businessLicenseAudit(Request $request)
    {
        $post = $request->only(['userid','licenceid','status']);
        $status = $post['status'];
        $status_de = ['TG'=>1,'BH'=>2,'JJ'=>3];
        $status_ok = [1,2,3];
        if(!in_array($status_de[$status],$status_ok)){
            return response()->json(['success'=>false,'code'=>'2','message'=>'没有此状态']);
        }
        $licen = Licence::find($post['licenceid']);
        if($licen->business_confirm!=0){
            return response()->json(['success'=>false,'code'=>'1','message'=>'当前状态无法修改！']);
        }
        $editData = [
            'business_confirm'=>$status_de[$status]
        ];
        $licence = new Licence();
        $licenresult = $licence->editAction($editData,$post['licenceid']);
        if(!$licenresult){
            return response()->json(['success'=>false,'code'=>'3','message'=>'操作失败，请稍后重试！']);
        }
        $licenData = Licence::find($post['licenceid']);
        if($licenData->identity_confirm==1 && $licenData->business_confirm==1 && $licenData->foodpermit_confirm==1){
            $userresult = (boolean)User::where('user_id',$post['userid'])->update(['reliability'=>2]);
            $mealshop = new MealShop;
            $existsshop = $mealshop->where('users_id',$post['userid'])->exists();
            if(!$existsshop){
                $shopresult = $mealshop->createShop(['shop_tel'=>User::where('user_id',$post['userid'])->value('tel')],$post['userid']);
                $filename = self::createQrcode($shopresult);
                $qrsul = $mealshop->where('shop_id',$shopresult)->update(['shop_qrcode'=>$filename]);
                if($shopresult && $qrsul){
                    return response()->json(['success'=>true,'code'=>0,'message'=>'操作成功']);
                }else{
                    return response()->json(['success'=>false,'code'=>'3','message'=>'操作失败，请稍后重试！']);
                }
            }
            if($userresult){
                return response()->json(['success'=>true,'code'=>0,'message'=>'操作成功']);
            }else{
                return response()->json(['success'=>false,'code'=>'3','message'=>'操作失败，请稍后重试！']);
            }
        }else{
            return response()->json(['success'=>true,'code'=>0,'message'=>'操作成功']);
        }
    }

    /**
     * 食品安全认证操作
     */
    public function foodSafetyAudit(Request $request)
    {
        $post = $request->only(['userid','licenceid','status']);
        $status = $post['status'];
        $status_de = ['TG'=>1,'BH'=>2,'JJ'=>3];
        $status_ok = [1,2,3];
        if(!in_array($status_de[$status],$status_ok)){
            return response()->json(['success'=>false,'code'=>'2','message'=>'没有此状态']);
        }
        $licen = Licence::find($post['licenceid']);
        if($licen->foodpermit_confirm!=0){
            return response()->json(['success'=>false,'code'=>'1','message'=>'当前状态无法修改！']);
        }
        $editData = [
            'foodpermit_confirm'=>$status_de[$status]
        ];
        $licence = new Licence();
        $licenresult = $licence->editAction($editData,$post['licenceid']);
        if(!$licenresult && $shopresult){
            return response()->json(['success'=>false,'code'=>'3','message'=>'操作失败，请稍后重试！']);
        }
        $licenData = Licence::find($post['licenceid']);
        if($licenData->identity_confirm==1 && $licenData->business_confirm==1 && $licenData->foodpermit_confirm==1){
            $userresult = (boolean)User::where('user_id',$post['userid'])->update(['reliability'=>2]);
            $mealshop = new MealShop;
            $existsshop = $mealshop->where('users_id',$post['userid'])->exists();
            if(!$existsshop){
                $shopresult = $mealshop->createShop(['shop_tel'=>User::where('user_id',$post['userid'])->value('tel')],$post['userid']);
                $filename = self::createQrcode($shopresult);
                $qrsul = $mealshop->where('shop_id',$shopresult)->update(['shop_qrcode'=>$filename]);
                if($shopresult && $qrsul){
                    return response()->json(['success'=>true,'code'=>0,'message'=>'操作成功']);
                }else{
                    return response()->json(['success'=>false,'code'=>'3','message'=>'操作失败，请稍后重试！']);
                }
            }
            if($userresult){
                return response()->json(['success'=>true,'code'=>0,'message'=>'操作成功']);
            }else{
                return response()->json(['success'=>false,'code'=>'3','message'=>'操作失败，请稍后重试！']);
            }
        }else{
            return response()->json(['success'=>true,'code'=>0,'message'=>'操作成功']);
        }
    }

    /**
     * 用户反馈信息
     */
    public function userFeedback(Request $request)
    {
        $feedback = new UserFeedback;
        $data = $feedback->getList();
        $feedbacks['col1']=[];
        $feedbacks['col2']=[];
        $feedbacks['col3']=[];
        $i = 1;
        foreach ($data as $value) {
            if($i==1){
                $feedbacks['col1'][] = $value;
            }else if($i==2){
                $feedbacks['col2'][] = $value;
            }else if($i==3){
                $feedbacks['col3'][] = $value;
            }
            $i = $i>=3?1:$i+1;
        }
        return view('user.feedback',['feedbacks'=>$feedbacks,'page'=>$data]);
    }

    /**
     * 加盟申请
     */
    public function getJoin(Request $request)
    {
        $joininfo = new JoinInfo;
        $data = $joininfo->getList();
        $feedbacks['col1']=[];
        $feedbacks['col2']=[];
        $feedbacks['col3']=[];
        $i = 1;
        foreach ($data as $value) {
            if($i==1){
                $feedbacks['col1'][] = $value;
            }else if($i==2){
                $feedbacks['col2'][] = $value;
            }else if($i==3){
                $feedbacks['col3'][] = $value;
            }
            $i = $i>=3?1:$i+1;
        }
        return view('user.join',['feedbacks'=>$feedbacks,'page'=>$data]);
    }

    /**
     * 二维码
     */
    public static function createQrcode($randstr,$logo=false,$save_=false)
    {
        if(!$logo){
            $logo = '/public/assets/img/logo2.png';
        }
        if(strtolower(substr(PHP_OS, 0, 3)) == 'win'){
            $pm = 'tmp\\';
        }else{
            $pm = 'tmp/';
        }
        $pathlogo = OSS::getPublicObjectURL(config('aliyun.BucketName'),'ShopQrcodeImg');
        $filename = md5(uniqid(microtime(true),true)).'.png';
        $savename = date('Ymd').'/'.$filename;
        $pathfile = 'ShopQrcodeImg/'.$savename;
        QrCode::format('png')
        ->size(300)
        ->margin(1)
        ->merge($logo,.15)
        ->generate('https://api-shop.jiashilexiang.cn/?shop_id='.$randstr, public_path($pm.$filename));
        if(!$save_){
            $a = OSS::publicUpload(config('aliyun.BucketName'),$pathfile,public_path('tmp/'.$filename));
        }
        @unlink(public_path($pm.$filename));
        return $savename;
    }

    public function shopqrcode()
    {
       $shops = DB::table('lexiang_meal_shop')->select('shop_id')->get();
       foreach ($shops as $key => $value) {
           $filename = self::createQrcode($value->shop_id);
           $r = DB::table('lexiang_meal_shop')->where('shop_id',$value->shop_id)->update(['shop_qrcode'=>$filename]);
           print_r($r);
       }
    }

    /**
     * 发卡剩余次数
     */
    public function selectCardOnce()
    {
        dd(MealUserCard::where('card_num','>',0)->where('card_invalid',1)->sum('card_num'));
    }

    /**
     * 红包分享列表
     */
    public function shareList(Request $request)
    {
        $share = new Share;
        $list = $share->where('toorme',1)
        ->selectRaw('*,null as share_user_name,null as me_user_name')
        ->paginate(15);

        return response()->json([
            'success'=>true,
            'code'=>'000',
            'message'=>'查询完成',
            'data'=>$list
        ]);
    }

    /**
     * 修改配送商圈
     */
    public function editCircle(Request $request)
    {
        $user = new User;
        $info = $user->where('user_id',$request->input('user_id'))->first();
        $info->circle_id = $request->input('circle_id');
        if($info->save()){
            return response()->json([
                'success'=>true,
                'code'=>'000',
                'message'=>'修改成功'
            ]);
        }else{
            return response()->json([
                'success'=>false,
                'code'=>'006',
                'message'=>'修改出错，请稍后再试！'
            ]);
        }
    }

    /**
     * 添加、获取地址
     */
    public function getAddress(Request $request)
    {
        $address = new Address;
    }
}
